package org.hum.scaffold.dubbo;

import java.io.IOException;

import javax.annotation.Resource;

import org.hum.scaffold.dubbo.util.UrlUtil;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcInvocation;
import com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol;

@ComponentScan({"org.hum.scaffold.dubbo"})
@SpringBootTest(classes = DubboInovkerTest.class)
@ImportResource({"classpath:dubbo/dubbo-consumer-demo.xml"})
public class DubboInovkerTest {
	
	@Resource(name = "demoRpcService")
	private DemoService demoService;

	@Test
	public void referenceTest() {
		ReferenceConfig<DemoService> ref = new ReferenceConfig<DemoService>();
        ref.setApplication(new ApplicationConfig("HumingTest"));
        ref.setUrl("dubbo://localhost:20880");
        ref.setProtocol("dubbo");
        ref.setInterface(DemoService.class);
        ref.setVersion(null);
        ref.setTimeout(100000);
        ref.setGroup(null);
        
        System.out.println(ref.get().sayHello("huming"));
	}

	/**
	 * @deprecated 暂时还不可用
	 */
	@Test
	@Deprecated
	public void reference2Test() throws RpcException, NoSuchMethodException, SecurityException {
		DubboProtocol dubboProtocol = new DubboProtocol();
		Invoker<DemoService> invoker = dubboProtocol.refer(DemoService.class, UrlUtil.toUrl("dubbo://localhost:20880/org.hum.scaffold.dubbo.DemoService?application=scaffold&default.timeout=10000000&dubbo=2.0.2&interface=org.hum.scaffold.dubbo.DemoService&methods=sayHello,sayHello2&pid=19632&protocol=dubbo&register.ip=192.168.0.102&serialization=kryo&side=consumer&timeout=10000000&timestamp=1618654669719rg.hum.scaffold.dubbo.DemoService?application=scaffold&default.timeout=10000000&dubbo=2.0.2&interface=org.hum.scaffold.dubbo.DemoService&methods=sayHello,sayHello2&pid=19632&protocol=dubbo&register.ip=192.168.0.102&serialization=kryo&side=consumer&timeout=10000000&timestamp=1618654669719"));
		Result result = invoker.invoke(new RpcInvocation(DemoService.class.getDeclaredMethod("sayHello", new Class[] { String.class }), new Object[] { "huming" }));
		System.out.println(result.getValue());
	}

	@Test
	public void springConsumer() throws IOException {
		SpringApplication.run(DubboInovkerTest.class);
		System.out.println("Server start");
		System.out.println(BaseHolder.getBean("demoRpcService", DemoService.class).sayHello("huming"));
	}
}
